package ipa

import (
	"bytes"
	"crypto/tls"
	"fmt"
	"net/http"
	"net/http/cookiejar"
	"net/url"
	"youdu/config"
)

func LoginFreeIPA(username, password string) error {
	ipaURL := config.Inst.Freeipa.Host + "/ipa/session/login_password"

	// Prepare form data
	form := url.Values{}
	form.Add("user", username)
	form.Add("password", password)

	// Create a cookie jar to handle cookies
	jar, err := cookiejar.New(nil)
	if err != nil {
		return fmt.Errorf("error creating cookie jar: %v", err)
	}

	// 创建忽略 SSL 证书验证的 HTTP 客户端
	tr := &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	}

	// Create an HTTP client with the cookie jar
	client := &http.Client{
		Jar:       jar,
		Transport: tr,
	}

	// Create the request
	req, err := http.NewRequest("POST", ipaURL, bytes.NewBufferString(form.Encode()))
	if err != nil {
		return fmt.Errorf("error creating request: %v", err)
	}

	// Set headers
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	req.Header.Set("Accept", "application/json")
	req.Header.Set("Referer", ipaURL)

	// Send the request
	resp, err := client.Do(req)
	if err != nil {
		return fmt.Errorf("error sending request: %v", err)
	}
	defer resp.Body.Close()

	// Check if login was successful
	if resp.StatusCode != http.StatusOK {
		return fmt.Errorf("login failed: %s", resp.Status)
	}

	// Parse the response
	// var result map[string]interface{}
	// if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
	// 	return fmt.Errorf("error decoding response: %v", err)
	// }

	// Print the result
	return nil
}
